package cn.witsky.rtp2ws.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NetWorkUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpDownLoad.class);

	public static boolean isValidIp(String host) {
		boolean isValid = false;
		if (host.equals("127.0.0.1")) {
			return isValid;
//			return true;
		}
		Enumeration allNetInterfaces = null;
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			logger.error("校验ip地址出现异常:",e);
		}
		InetAddress ip = null;
		NetworkInterface netInterface = null;
		Enumeration<InetAddress> addresses = null;
		if (allNetInterfaces != null) {
			while (allNetInterfaces.hasMoreElements()) {
				if (isValid) {
					break;
				}
				netInterface = (NetworkInterface) allNetInterfaces.nextElement();
				addresses = netInterface.getInetAddresses();
				while (addresses.hasMoreElements()) {
					ip = (InetAddress) addresses.nextElement();
					if (ip != null && ip instanceof Inet4Address) {
						if (ip.getHostAddress().equals(host)) {
							isValid = true;
							break;
						}

					}
				}
			}
		}
		return isValid;
	}

//	/**
//	 * 
//	 * 取出域名
//	 * 
//	 * @param url
//	 * @return
//	 */
//	public static String getDomain(String url) {
//		try {
//			Pattern p = Pattern.compile("[^//]*$?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE);
//			Matcher matcher = p.matcher(url);
//			matcher = p.matcher(url);
//			matcher.find();
//			return matcher.group();
//		} catch (Exception ex) {
//			logger.error("获取域名错误");
//			return "";
//		}
//	}
	
	
	public static String getDomain(String url) {
		URI  uri=null;
		try {
			uri=new URI(url);
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		URI effectiveURI=null;
		if(uri!=null) {
			try {
				effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
			} catch (Throwable var4) {
				effectiveURI = null;
			}
		}
		if(effectiveURI!=null) {
			return effectiveURI.toString().split("//")[1];
		}else {
			return "";
		}
	}
	
	public static void main(String args[]) {
		String test=NetWorkUtil.getDomain("http://10.137.172.158:20002/V2/20211012113811/ALI_A44616503232a7051_15934319899_18888888888_20211012113811.mp3");
		System.out.println(test);
	}
}
